package com.fowo.api.syncAmazon.api;

import cn.hutool.core.date.DateUtil;
import com.amazon.spapi.api.OrdersV0Api;
import com.amazon.spapi.api.ReportsApi;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.orders.*;
import com.amazon.spapi.model.reports.CreateReportSpecification;
import com.amazon.spapi.model.reports.Report;
import com.amazon.spapi.model.reports.ReportDocument;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.entity.ListingFather;
import com.fowo.api.entity.Product;
import com.fowo.api.entity.ShopInfo;
import com.fowo.api.entity.TmpSalesStatement;
import com.fowo.api.mapper.ListingFatherMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.SysRegionMapper;
import com.fowo.api.service.SysRegionService;
import com.fowo.api.service.TmpSalesStatementService;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.service.impl.SysRegionServiceImpl;
import com.fowo.api.service.impl.TmpSalesStatementServiceImpl;
import com.fowo.api.syncAmazon.entity.TmpSellOrder;
import com.fowo.api.syncAmazon.entity.TmpSellOrderDetail;
import com.fowo.api.syncAmazon.mapper.TmpSellOrderMapper;
import com.fowo.api.syncAmazon.service.impl.TmpSellOrderDetailServiceImpl;
import com.fowo.api.syncAmazon.util.AmazonUtil;
import com.fowo.api.syncAmazon.util.AmzDateUtils;
import com.fowo.api.syncAmazon.util.GeneralUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.squareup.okhttp.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;

@Slf4j
@Component
public class OrderService extends ReportService {

    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private AmazonUtil amazonUtil;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private TmpSellOrderDetailServiceImpl tmpSellOrderDetailService;
    @Resource
    private TmpSalesStatementServiceImpl tmpSalesStatementService;
    @Resource
    private TmpSellOrderMapper tmpSellOrderMapper;
    @Resource
    private ListingFatherMapper listingFatherMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private SysRegionServiceImpl sysRegionService;

    /**
     * 获取订单
     * @throws ApiException
     */
    public List<TmpSellOrder> getOrder() throws Exception {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        final List<ShopInfo> shopList = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"Amazon")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
        List<TmpSellOrder> temSellOrderList = new ArrayList<>();
        for(ShopInfo shop : shopList){
            long start_time_ms = System.currentTimeMillis();
            log.info("开始拉去店铺："+shop.getShopName());
            sysRegionService.getById(shop.getMid());
            OrdersV0Api ordersV0Api = amazonUtil.getOrdersV0Api(entityAuthority,shop);

            List<String> marketplaceIds = Arrays.asList(shop.getMarketplaceId().split(","));
            String createdAfter = DateUtil.formatDate(DateUtil.offsetDay(new Date(),-30));
//            String createdAfter = "2023-11-20";
            String createdBefore = null;
            String lastUpdatedAfter = null;
            String lastUpdatedBefore = null;
            List<String> orderStatuses = null;
            List<String> fulfillmentChannels = null;
            List<String> paymentMethods = null;
            String buyerEmail = null;
            String sellerOrderId = null;
            Integer maxResultsPerPage = null;
            List<String> easyShipShipmentStatuses = null;
            String nextToken = null;
            List<String> amazonOrderIds = null;
            String actualFulfillmentSupplySourceId = null;
            Boolean isISPU = null;
            String storeChainStoreId = null;
            GetOrdersResponse response = ordersV0Api.getOrders(marketplaceIds, createdAfter, createdBefore, lastUpdatedAfter, lastUpdatedBefore,
                    orderStatuses, fulfillmentChannels, paymentMethods, buyerEmail, sellerOrderId, maxResultsPerPage, easyShipShipmentStatuses, nextToken, amazonOrderIds, actualFulfillmentSupplySourceId, isISPU, storeChainStoreId);
//            System.out.println(response.toString());
            final OrdersList payload = response.getPayload();
            OrderList orders = payload.getOrders();
            if(StringUtils.isNotBlank(payload.getNextToken())){ // 下页token
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                nextToken = payload.getNextToken();
                OrderList orderList = getNext(ordersV0Api,marketplaceIds, createdAfter, createdBefore, lastUpdatedAfter, lastUpdatedBefore, orderStatuses, fulfillmentChannels, paymentMethods, buyerEmail, sellerOrderId, maxResultsPerPage, easyShipShipmentStatuses, nextToken, amazonOrderIds, actualFulfillmentSupplySourceId, isISPU, storeChainStoreId);
                orders.addAll(orderList);
            }
            long end_time_ms = System.currentTimeMillis();
            log.info("拉取店铺："+shop.getShopName()+"完成，耗时："+(end_time_ms-start_time_ms)+"毫秒");
            temSellOrderList.addAll(buildData(orders,shop));
        }

        //批量添加或修改订单明细
//        List<List<TmpSellOrderDetail>> partition = Lists.partition(tmpSellOrderDetailList, 200);
//        for (List<TmpSellOrderDetail> list:partition) {
//            if(tmpSellOrderDetailService.saveBatch(list)){
//                tmpSellOrderMapper.insertOrderDetail();
//                tmpSellOrderMapper.updateOrderDetail();
//            }
//        }
        return temSellOrderList;
    }
    /**
     * 下一页订单
     * @param ordersV0Api
     * @param marketplaceIds
     * @param createdAfter
     * @param createdBefore
     * @param lastUpdatedAfter
     * @param lastUpdatedBefore
     * @param orderStatuses
     * @param fulfillmentChannels
     * @param paymentMethods
     * @param buyerEmail
     * @param sellerOrderId
     * @param maxResultsPerPage
     * @param easyShipShipmentStatuses
     * @param nextToken
     * @param amazonOrderIds
     * @param actualFulfillmentSupplySourceId
     * @param isISPU
     * @param storeChainStoreId
     * @return
     * @throws ApiException
     */
    public OrderList getNext(OrdersV0Api ordersV0Api,List<String> marketplaceIds, String createdAfter, String createdBefore, String lastUpdatedAfter, String lastUpdatedBefore, List<String> orderStatuses, List<String> fulfillmentChannels, List<String> paymentMethods, String buyerEmail, String sellerOrderId, Integer maxResultsPerPage, List<String> easyShipShipmentStatuses, String nextToken, List<String> amazonOrderIds, String actualFulfillmentSupplySourceId, Boolean isISPU, String storeChainStoreId) throws ApiException {
        GetOrdersResponse response = ordersV0Api.getOrders(marketplaceIds, createdAfter, createdBefore, lastUpdatedAfter, lastUpdatedBefore, orderStatuses, fulfillmentChannels, paymentMethods, buyerEmail, sellerOrderId, maxResultsPerPage, easyShipShipmentStatuses, nextToken, amazonOrderIds, actualFulfillmentSupplySourceId, isISPU, storeChainStoreId);
        final OrdersList payload = response.getPayload();
        OrderList orders = payload.getOrders();
        if(StringUtils.isNotBlank(payload.getNextToken())){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            nextToken = payload.getNextToken();
            OrderList orderList = getNext(ordersV0Api,marketplaceIds, createdAfter, createdBefore, lastUpdatedAfter, lastUpdatedBefore, orderStatuses, fulfillmentChannels, paymentMethods, buyerEmail, sellerOrderId, maxResultsPerPage, easyShipShipmentStatuses, nextToken, amazonOrderIds, actualFulfillmentSupplySourceId, isISPU, storeChainStoreId);
            orders.addAll(orderList);
        }
        return orders;
    }

    public List<TmpSellOrder> buildData(OrderList orders,ShopInfo shop) throws Exception {
        log.info("拉取亚马逊订单数据完成，开始处理数据");
        List<TmpSellOrder> list = new ArrayList<>();
        TmpSellOrder sellOrder;
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(Order order : orders){
            sellOrder = new TmpSellOrder();
            sellOrder.setAmazonOrderId(order.getAmazonOrderId());
            sellOrder.setSid(shop.getId());
            sellOrder.setCountry(shop.getMid());
            if(null != order.getBuyerInfo()){
                sellOrder.setBuyerName(order.getBuyerInfo().getBuyerName());
                sellOrder.setBuyerEmail(order.getBuyerInfo().getBuyerEmail());
            }
            if(null != order.getOrderTotal()){
                sellOrder.setOrderTotalAmount(order.getOrderTotal().getAmount());
                sellOrder.setCurrency(order.getOrderTotal().getCurrencyCode());
            }
//            sellOrder.setPurchaseDateLocal(simpleDateFormat.parse(order.getPurchaseDate()
//                    .replace("T"," ")
//                    .replace("Z","")));
            sellOrder.setPurchaseDateLocal(AmzDateUtils.getDatePlus(order.getPurchaseDate()));
//            sellOrder.setRemark("");
            sellOrder.setRequestReviewStatus("0");
            sellOrder.setOrderStatus(order.getOrderStatus().getValue());
            if(null != order.getFulfillmentChannel()){
                sellOrder.setFulfillmentChannel(order.getFulfillmentChannel().getValue());
            }
            sellOrder.setIsAssessed(false);
            sellOrder.setIsMcfOrder(false);
            sellOrder.setIsReturnOrder(false);
            sellOrder.setIsReplacedOrder(StringUtils.isNotBlank(order.getReplacedOrderId()));
            sellOrder.setIsReplacementOrder(order.isIsReplacementOrder());
//            sellOrder.setLastUpdateDate(simpleDateFormat.parse(order.getLastUpdateDate()
//                    .replace("T"," ")
//                    .replace("Z","")));
            sellOrder.setLastUpdateDate(AmzDateUtils.getDatePlus(order.getLastUpdateDate()));
//            sellOrder.setPostedDate();
            if(null != order.getShippingAddress()){
                sellOrder.setAddress(order.getShippingAddress().getAddressLine1());
                sellOrder.setPostalCode(order.getShippingAddress().getPostalCode());
                sellOrder.setName(order.getShippingAddress().getName());
                sellOrder.setPhone(order.getShippingAddress().getPhone());
            }
            if(null != order.getDefaultShipFromLocationAddress()){
                sellOrder.setShippingAddress(order.getDefaultShipFromLocationAddress().getAddressLine1());
            }
            sellOrder.setIsBusinessOrder(order.isIsBusinessOrder());
            sellOrder.setIsPrime(order.isIsPrime());
            sellOrder.setIsPremiumOrder(order.isIsPremiumOrder());
            sellOrder.setSalesChannel(order.getSalesChannel());
            sellOrder.setShipServiceLevel(order.getShipServiceLevel());
            sellOrder.setPaymentMethod(order.getPaymentMethod() == null? null : order.getPaymentMethod().getValue());
            sellOrder.setEarliestShipDate(AmzDateUtils.getDatePlus(order.getEarliestShipDate()));
            sellOrder.setLatestShipDate(AmzDateUtils.getDatePlus(order.getLatestShipDate()));
            sellOrder.setEarliestDeliveryDate(AmzDateUtils.getDatePlus(order.getEarliestDeliveryDate()));
            sellOrder.setLatestDeliveryDate(AmzDateUtils.getDatePlus(order.getLatestDeliveryDate()));
//            sellOrder.setIsPromotion(false);
//            sellOrder.setTaxesIncluded();
            list.add(sellOrder);
        }
        return list;
    }

    /**
     * 拉取订单详情
     * @param tmpSellOrderList
     * @throws ApiException
     */
    public List<TmpSellOrderDetail> getOrderDetails(List<TmpSellOrder> tmpSellOrderList) throws Exception {

        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        List<TmpSellOrderDetail> result = new ArrayList<>();
        for(TmpSellOrder order : tmpSellOrderList){
            final ShopInfo shop = shopInfoService.getById(order.getSid());
            OrdersV0Api ordersV0Api = amazonUtil.getOrdersV0Api(entityAuthority,shop);

            GetOrderItemsResponse response = ordersV0Api.getOrderItems(order.getAmazonOrderId(),null);
            if(response.getPayload() != null){
                OrderItemList orderItemList = response.getPayload().getOrderItems();
                if(StringUtils.isNotBlank(response.getPayload().getNextToken())){ //下一页
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    OrderItemList next = getNextOrderItem(ordersV0Api,order.getAmazonOrderId(),response.getPayload().getNextToken());
                    orderItemList.addAll(next);
                }
                List<TmpSellOrderDetail> tmpSellOrderDetailList = buildTemSellOrderDetail(orderItemList,order.getAmazonOrderId(), shop);
                result.addAll(tmpSellOrderDetailList);
            }
        }
        return result;
    }

    /**
     * 下一页
     * @param ordersV0Api
     * @param amazonOrderId
     * @param nextToken
     * @return
     * @throws ApiException
     */
    public OrderItemList getNextOrderItem(OrdersV0Api ordersV0Api,String amazonOrderId,String nextToken) throws ApiException {
        GetOrderItemsResponse response = ordersV0Api.getOrderItems(amazonOrderId,nextToken);
        if(null != response.getPayload()){
            OrderItemList orderItems = response.getPayload().getOrderItems();
            if(StringUtils.isNotBlank(response.getPayload().getNextToken())){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                OrderItemList next = getNextOrderItem(ordersV0Api,amazonOrderId,response.getPayload().getNextToken());
                orderItems.addAll(next);
            }
            return orderItems;
        }
        return null;
    }

    public List<TmpSellOrderDetail> buildTemSellOrderDetail(OrderItemList orderItemList,String amazonOrderId,ShopInfo shop)throws Exception {
        List<TmpSellOrderDetail> result = new ArrayList<>();
        TmpSellOrderDetail detail;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(OrderItem orderItem : orderItemList){
            final ListingFather listingFather = listingFatherMapper.selectOne(Wrappers.lambdaQuery(ListingFather.class)
                    .eq(ListingFather::getShop, shop.getId())
                    .eq(ListingFather::getMsku, orderItem.getSellerSKU()));
            Product product = new Product();
            if(null != listingFather && null != listingFather.getPairProduct()){
                product = productMapper.selectById(listingFather.getPairProduct());
            }
            detail = new TmpSellOrderDetail();
            detail.setImg(product.getPicUrl());
            detail.setAmazonOrderId(amazonOrderId);
            detail.setTitle(orderItem.getTitle());
            detail.setAsin(orderItem.getASIN());
            detail.setAsinUrl("");
            detail.setSellerSku(orderItem.getSellerSKU());
            detail.setProductName(product.getName());
            detail.setSku(product.getSku());
            detail.setProductId(product.getId());

            BigDecimal itemPrice = orderItem.getItemPrice()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getItemPrice().getAmount());
            detail.setUnitPriceAmount(itemPrice);
            String currencyCode = orderItem.getItemPrice()==null ? "" : orderItem.getItemPrice().getCurrencyCode();
            detail.setFeeCurrency(currencyCode);

            detail.setQuantityOrdered(orderItem.getQuantityOrdered());
            detail.setQuantityShipped(orderItem.getQuantityShipped());

            BigDecimal taxAmount = orderItem.getItemTax()==null?BigDecimal.ZERO: new BigDecimal(orderItem.getItemTax().getAmount());
            detail.setTaxAmount(taxAmount);

            BigDecimal shippingPrice = orderItem.getShippingPrice()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getShippingPrice().getAmount());
            BigDecimal salesPriceAmount = itemPrice.add(taxAmount).add(shippingPrice);
            detail.setSalesPriceAmount(salesPriceAmount);

            detail.setCgPrice(product.getProcurementCost());
//            detail.setCgTransportCosts(product.getProcurementCost());
//            detail.setFbaShipmentAmount();
            detail.setPromotionAmount(orderItem.getPromotionDiscount()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getPromotionDiscount().getAmount()));
            detail.setPromotionIds(orderItem.getPromotionIds()==null?"":Joiner.on(",").join(orderItem.getPromotionIds()));
//            detail.setCommissionAmount();
//            detail.setFeeCostAmount();
//            detail.setProfit();
            detail.setOrderItemId(orderItem.getOrderItemId());
//            detail.setItemPriceAmount(itemPrice);
//            detail.setItemTaxAmount(taxAmount);
            detail.setShippingPriceAmount(shippingPrice);
            detail.setShippingTaxAmount(orderItem.getShippingTax()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getShippingTax().getAmount()));
            detail.setShippingDiscountAmount(orderItem.getShippingDiscount()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getShippingDiscount().getAmount()));
            detail.setShippingDiscountTaxAmount(orderItem.getShippingDiscountTax()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getShippingDiscountTax().getAmount()));
            detail.setCodFeeAmount(orderItem.getCoDFee()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getCoDFee().getAmount()));
            detail.setPromotionDiscountAmount(orderItem.getPromotionDiscount()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getPromotionDiscount().getAmount()));
            detail.setPromotionDiscountTaxAmount(orderItem.getPromotionDiscountTax()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getPromotionDiscountTax().getAmount()));
            detail.setCodFeeDiscountAmount(orderItem.getCoDFeeDiscount()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getCoDFeeDiscount().getAmount()));
            if(null != orderItem.getBuyerInfo()){
                final ItemBuyerInfo buyerInfo = orderItem.getBuyerInfo();
                detail.setGiftWrapPriceAmount(buyerInfo.getGiftWrapPrice()==null?BigDecimal.ZERO:new BigDecimal(buyerInfo.getGiftWrapPrice().getAmount()));
                detail.setGiftWrapTaxAmount(buyerInfo.getGiftWrapTax()==null?BigDecimal.ZERO:new BigDecimal(buyerInfo.getGiftWrapTax().getAmount()));
                detail.setGiftMessageText(buyerInfo.getGiftMessageText());
                detail.setGiftWrapLevel(buyerInfo.getGiftWrapLevel());
            }
            detail.setConditionNote(orderItem.getConditionNote());
            detail.setConditionId(orderItem.getConditionId());
            detail.setConditionSubtypeId(orderItem.getConditionSubtypeId());
            if(StringUtils.isNotBlank(orderItem.getScheduledDeliveryStartDate())){
                detail.setScheduledDeliveryStartDate(simpleDateFormat.parse(orderItem.getScheduledDeliveryStartDate().replace("T"," ").replace("Z","")));
            }
            if(StringUtils.isNotBlank(orderItem.getScheduledDeliveryEndDate())){
                detail.setScheduledDeliveryEndDate(simpleDateFormat.parse(orderItem.getScheduledDeliveryEndDate().replace("T"," ").replace("Z","")));
            }
            detail.setPriceDesignation(orderItem.getPriceDesignation());
            if(null != orderItem.getPointsGranted() && null != orderItem.getPointsGranted().getPointsMonetaryValue()){
                BigDecimal pointsMonetaryValueAmount = orderItem.getPointsGranted().getPointsMonetaryValue().getAmount() == null
                        ? BigDecimal.ZERO
                        : new BigDecimal(orderItem.getPointsGranted().getPointsMonetaryValue().getAmount());
                detail.setPointsMonetaryValueAmount(pointsMonetaryValueAmount);
            }
            result.add(detail);
        }
        return result;
    }


    /**
     * 销售统计 数据
     * @throws Exception
     */
    public void getOrderReport() throws Exception {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"Amazon")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
        for(ShopInfo shop : list){

            List<String> marketplaceIds = Arrays.asList(shop.getMarketplaceId().split(","));

            CreateReportSpecification body = new CreateReportSpecification();
            body.setReportType("GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL");
            body.setMarketplaceIds(marketplaceIds);
            body.setDataStartTime(AmzDateUtils.getOffsetDateTimeUTC(DateUtil.beginOfDay(DateUtil.yesterday())));
            body.setDataEndTime(AmzDateUtils.getOffsetDateTimeUTC(DateUtil.endOfDay(DateUtil.yesterday())));

//            Calendar cstart=Calendar.getInstance();
//            cstart.add(Calendar.DATE, -45);
//            body.setDataStartTime(AmzDateUtils.getOffsetDateTimeUTC(cstart));
//            Calendar cend=Calendar.getInstance();
//            cend.add(Calendar.DATE, -15);
//            body.setDataEndTime(AmzDateUtils.getOffsetDateTimeUTC(cend));

            // 第一步 创建报告
            ReportsApi reportsApi = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
            final String reportId = createReport(reportsApi, body);
            // 第二步 检验报告是否完成
            ReportsApi reportsApi2 = amazonUtil.getReportsApi(entityAuthority,shop,2.0);
            final Report report = getReport(reportsApi2, reportId);
            // 第三步 获取报告连接
            ReportsApi reportsApi3 = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
            final ReportDocument reportDocument = reportsApi3.getReportDocument(report.getReportDocumentId());
            // 第四步 下载报告
            String compressionAlgorithm = null;
            if(null != reportDocument.getCompressionAlgorithm()){
                compressionAlgorithm = reportDocument.getCompressionAlgorithm().getValue();
            }
            download(reportDocument.getUrl(),compressionAlgorithm,shop);

        }
    }

    /**
     * 下载报告
     * @param url
     * @param compressionAlgorithm
     * @throws IOException
     * @throws IllegalArgumentException
     */
    public void download(String url, String compressionAlgorithm,ShopInfo shop) throws IOException, IllegalArgumentException {
        OkHttpClient httpclient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = httpclient.newCall(request).execute();
        if (!response.isSuccessful()) {
            System.out.println(
                    String.format("Call to download content was unsuccessful with response code: %d and message: %s",
                            response.code(), response.message()));
            return;
        }

        try (ResponseBody responseBody = response.body()) {
            MediaType mediaType = MediaType.parse(response.header("Content-Type"));
            Charset charset = mediaType.charset();
            if (charset == null) {
                throw new IllegalArgumentException(String.format(
                        "Could not parse character set from '%s'", mediaType.toString()));
            }

            Closeable closeThis = null;
            try {
                InputStream inputStream = responseBody.byteStream();
                closeThis = inputStream;

                if ("GZIP".equals(compressionAlgorithm)) {
                    inputStream = new GZIPInputStream(inputStream);
                    closeThis = inputStream;
                }

                // This example assumes that the download content has a charset in the content-type header, e.g.
                // text/plain; charset=UTF-8
                if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                    closeThis = inputStreamReader;

                    BufferedReader reader = new BufferedReader(inputStreamReader);
                    closeThis = reader;

                    int lineNumber = 0;
                    String line;
                    Map<String,Integer> titleList = new HashMap<String,Integer>();
                    List<TmpSalesStatement> list = new ArrayList<>();
                    while ((line = reader.readLine()) != null) {
//                        line = reader.readLine();
                        String[] info = line.split("\t");
                        int length = info.length;
                        if (lineNumber == 0) {
                            for (int i = 0; i < length; i++) {
                                titleList.put(info[i],i);
                            }
                        } else {
                            String order_status= GeneralUtil.getStrValue(info, titleList, "order-status");
                            if(!order_status.equals("Shipped")
                                    && !order_status.equals("Unshipped")
                                    && !order_status.equals("Pending")){
                                continue;
                            }
                            TmpSalesStatement tmp = new TmpSalesStatement();
                            tmp.setSid(shop.getId());
                            tmp.setCreateTime(new Date());
                            String amazon_order_id= GeneralUtil.getStrValue(info, titleList, "amazon-order-id");
                            String merchant_order_id= GeneralUtil.getStrValue(info, titleList, "merchant-order-id");
                            String purchase_date= GeneralUtil.getStrValue(info, titleList, "purchase-date");
                            String last_updated_date= GeneralUtil.getStrValue(info, titleList, "last-updated-date");
//                            String order_status= GeneralUtil.getStrValue(info, titleList, "order-status");
                            String fulfillment_channel= GeneralUtil.getStrValue(info, titleList, "fulfillment-channel");
                            String sales_channel = GeneralUtil.getStrValue(info, titleList, "sales-channel");
                            String order_channel = GeneralUtil.getStrValue(info, titleList, "order-channel");
//                            String url = GeneralUtil.getStrValue(info, titleList, "url");
                            String ship_service_level= GeneralUtil.getStrValue(info, titleList, "ship-service-level");
                            String product_name= GeneralUtil.getStrValue(info, titleList, "product-name");
                            String sku= GeneralUtil.getStrValue(info, titleList, "sku");
                            String asin= GeneralUtil.getStrValue(info, titleList, "asin");
                            String item_status= GeneralUtil.getStrValue(info, titleList, "item-status");
                            String quantity= GeneralUtil.getStrValue(info, titleList, "quantity");
                            String currency= GeneralUtil.getStrValue(info, titleList, "currency");
                            BigDecimal item_price= GeneralUtil.getBigDecimalValue(info, titleList, "item-price");
                            BigDecimal item_tax= GeneralUtil.getBigDecimalValue(info, titleList, "item-tax");
                            BigDecimal shipping_price= GeneralUtil.getBigDecimalValue(info, titleList, "shipping-price");
                            BigDecimal shipping_tax= GeneralUtil.getBigDecimalValue(info, titleList, "shipping-tax");
                            BigDecimal gift_wrap_price= GeneralUtil.getBigDecimalValue(info, titleList, "gift-wrap-price");
                            BigDecimal gift_wrap_tax= GeneralUtil.getBigDecimalValue(info, titleList, "gift-wrap-tax");
                            BigDecimal item_promotion_discount= GeneralUtil.getBigDecimalValue(info, titleList, "item-promotion-discount");
                            BigDecimal ship_promotion_discount= GeneralUtil.getBigDecimalValue(info, titleList, "ship-promotion-discount");
                            String ship_city= GeneralUtil.getStrValue(info, titleList, "ship-city");
                            String ship_state= GeneralUtil.getStrValue(info, titleList, "ship-state");
                            String ship_postal_code= GeneralUtil.getStrValue(info, titleList, "ship-postal-code");
                            String ship_country= GeneralUtil.getStrValue(info, titleList, "ship-country");
                            String promotion_ids= GeneralUtil.getStrValue(info, titleList, "promotion-ids");
                            Boolean is_business_order= GeneralUtil.getBooleanValue(info, titleList, "is-business-order");
                            String purchase_order_number= GeneralUtil.getStrValue(info, titleList, "purchase-order-number");
                            String price_designation= GeneralUtil.getStrValue(info, titleList, "price-designation");
                            Boolean signature_confirmation_recommended = GeneralUtil.getBooleanValue(info, titleList, "signature-confirmation-recommended ");

                            tmp.setAmazonOrderId(amazon_order_id);
                            tmp.setMerchantOrderId(merchant_order_id);
                            tmp.setPurchaseDate(GeneralUtil.getDatePlus(purchase_date,ship_country));
                            tmp.setLastUpdatedDate(GeneralUtil.getDatePlus(last_updated_date,ship_country));
                            tmp.setOrderStatus(order_status);
                            tmp.setFulfillmentChannel(fulfillment_channel);
                            tmp.setSalesChannel(sales_channel);
                            tmp.setOrderChannel(order_channel);
                            tmp.setShipServiceLevel(ship_service_level);
                            tmp.setProductName(product_name);
                            tmp.setMsku(sku);
                            tmp.setAsin(asin);
                            tmp.setItemStatus(item_status);
                            tmp.setQuantity(quantity);
                            tmp.setCurrency(currency);
                            tmp.setItemPrice(item_price);
                            tmp.setItemTax(item_tax);
                            tmp.setShippingPrice(shipping_price);
                            tmp.setShippingTax(shipping_tax);
                            tmp.setGiftWrapPrice(gift_wrap_price);
                            tmp.setGiftWrapTax(gift_wrap_tax);
                            tmp.setItemPromotionDiscount(item_promotion_discount);
                            tmp.setShipCity(ship_city);
                            tmp.setShipState(ship_state);
                            tmp.setShipPostalCode(ship_postal_code);
                            tmp.setShipCountry(ship_country);
                            tmp.setPromotionIds(promotion_ids);
                            tmp.setIsBusinessOrder(is_business_order);
                            tmp.setPurchaseOrderNumber(purchase_order_number);
                            tmp.setPriceDesignation(price_designation);
                            tmp.setSignatureConfirmationRecommended(signature_confirmation_recommended);

                            list.add(tmp);
                        }
                        lineNumber++;
                        // Process line by line.
                    }
                    tmpSalesStatementService.saveBatch(list);
                } else {
                    //Handle content with binary data/other media types here.
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.error("处理Listing数据异常",e);
            } finally {
                if (closeThis != null) {
                    closeThis.close();
                }
            }
        }
    }
}
